import { storage } from '@/utils/index.js';
import { langs } from '@/locale/language.js';

const uploadFile = (url, params) => {
	const token = storage.getItem('token');
	const langSys = uni.getLocale();
	const langInfo = langs.find(item => item.code == langSys) || langs[0];
	const retries = 3;
	
	if (langInfo) {
		params.formData = Object.assign({}, {language: langInfo.type}, params.formData);
	}
	
	return new Promise((resolve, reject) => {
		function attemptRequest(attempt) {
			const uploadTask = uni.uploadFile({
				url,
				...params,
				header: {
					'x-token': token,
				},
				success(res) {
					if (res.statusCode === 200) {
						const data = JSON.parse(res.data);
						
						resolve(data);
					} else {
						reject(new Error('上传失败'));
					}
				},
				fail(err) {
					console.log(err);
					// if (attempt < retries) {
					// 	attemptRequest(attempt + 1);
					// } else {
						reject(err);
					// }
				}
			});
			
			uploadStore().addUploadTask(uploadTask);
		}

		attemptRequest(0);
	});
}

export {
	uploadFile
}